package com.example;

import org.junit.Test;

import java.lang.reflect.Field;
import java.util.Date;

public class ReflectionFieldDemo {

    // 反射：public String name = "Allen";
    @Test
    public void test1() throws Exception {
        Class<Person> personClass = Person.class;
        Person person = personClass.newInstance();
        Field field = personClass.getField("name");
        String value = (String) field.get(person);
        System.out.println(value);

        // 设置字段值
        field.set(person, "Alice");
        System.out.println(person.name);
    }

    // 反射：private int age = 18;
    @Test
    public void test2() throws Exception {
        Class<Person> personClass = Person.class;
        Person person = personClass.newInstance();
        Field field = personClass.getDeclaredField("age");
        field.setAccessible(true);
        int age = (Integer) field.get(person);
        System.out.println(age);

        // 设置字段值
        field.set(person, 28);
        System.out.println(person.getAge());
    }

    // 反射：public static Date time;
    @Test
    public void test3() throws Exception {
        Class<Person> personClass = Person.class;
        Field field = personClass.getField("time");

        // 设置字段值
        field.set(null, new Date());
        System.out.println(Person.time);
    }

}
